package com.jasonchoi.gateway;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义的GatewayFilterFactory 命名必须为XXXGatewayFilterFactory
 * @Author: JasonChoi
 * @Date: 2019/12/18 15:37
 */
@Component
public class ExampleGatewayFilterFactory extends AbstractGatewayFilterFactory<ExampleGatewayFilterFactory.Config> {
    private static final Log log = LogFactory.getLog(ExampleGatewayFilterFactory.class);
    private static final String CONFIG_ENABLE = "enable";

    public ExampleGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(CONFIG_ENABLE);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    if (config.isEnable()) {
                        log.info("MyCustomFilterFactory --> 自定义工厂开启 " + exchange.getRequest().getURI().getRawPath());
                    }
                })
        );
    }

    public static class Config {
        private boolean enable;

        public boolean isEnable() {
            return enable;
        }

        public void setEnable(boolean enable) {
            this.enable = enable;
        }
    }
}
